<template>
  <view class="box position-relative">
    <!-- <view v-if="!userInfo.mobile" class="position-absolute left-0"
      style="width: 100%; height: 100%; z-index: 9999;top: 200rpx;" @click="login.open()"></view> -->
    <uv-navbar placeholder title="商品详情" :autoBack="true"></uv-navbar>
    <view>
      <uv-swiper :list="formData.detailData.slider_image" height="750rpx"></uv-swiper>
    </view>
    <view class="p-x-32 m-t-36">
      <view class="flex justify-between align-ali">
        <view class="font-38 font-weight-bold">{{ formData.detailData.product_name || '--' }}</view>
        <!-- <view class="flex align-ali">
          <view class="m-r-5">
            <uv-image width="44rpx" :src="ASSETSURL + 'collect.png'" mode="widthFix"></uv-image>
          </view>
          <view class="font-30 font-weight-middles">收藏</view>
        </view> -->
      </view>
      <view class="font-26 m-t-20 collect-text">
        {{ formData.detailData.brief || '--' }}
      </view>
      <!-- 新人优惠劵 -->
      <view class="m-t-28" @click="goPages('/pagesA/pages/myDesign/coupon')">
        <uv-image width="686rpx" :src="ASSETSURL + 'newcomers.png'" mode="widthFix"></uv-image>
      </view>
      <!-- <view class="m-t-40 flex">
        <view class="flex material align-ali justify-cen">
          <view class="font-28 text-greey">材质</view>
          <view class="m-x-50">
            <uv-line direction="col" color="#D9D9D9" length="30rpx"></uv-line>
          </view>
          <view class="font-28 text-000">{{
            formData.detailData.material || '--'
          }}</view>
        </view>
        <view class="flex material align-ali justify-cen m-l-42">
          <view class="font-28 text-greey">产地</view>
          <view class="m-x-50">
            <uv-line direction="col" color="#D9D9D9" length="30rpx"></uv-line>
          </view>
          <view class="font-28 text-000">{{
            formData.detailData.producer || '--'
          }}</view>
        </view>
      </view> -->
      <!-- <view class="prodTitle m-t-45">
        <view class="prodTitleText p-l-28 font-32 position-relative font-weight-bold">保养材料</view>
        <view class="flex m-t-30">
          <!-- <view v-for="(item, index) in 4" :key="index" class="icon m-r-36">
            <uv-image width="104rpx" height="116rpx" :src="ASSETSURL + `material_0${index + 1}.png`"></uv-image>
          </view> --
          <uv-parse :content="formData.detailData.upkeep"></uv-parse>
        </view>
      </view> -->
    </view>
    <view class="prodTitle m-t-32">
      <view class="prodTitleText m-x-32 p-l-28 font-32 position-relative font-weight-bold">详情</view>
      <view class="m-t-30 p-x-32">
        <!-- <view v-for="(item, index) in 1" :key="index" class="icon">
          <uv-image width="750rpx" height="750rpx" :src="ASSETSURL + `xq.png`"></uv-image>
        </view> -->
        <uv-parse :content="formData.detailData.description"></uv-parse>
      </view>
    </view>
    <view class="m-t-36">
      <!-- <uv-parse :content="formData.detailData.note"></uv-parse> -->
	  <uv-collapse :border="false">
	  	<view v-for="(item, index) in msgList" :key="index">
			<uv-collapse-item :title="item.name">
			  <up-parse :content="item.content"></up-parse>
			</uv-collapse-item>
			<uv-line v-if="index != msgList.length - 1" class="m-x-32" style="width: auto" color="#D9D9D9"></uv-line>
	  	</view>
	  </uv-collapse>
    </view>
    <uv-popup ref="popup" mode="bottom" zIndex="99">
      <view class="specifications m-40 m-b-100">
        <view class="flex align-ali">
          <view>
            <uv-image width="142rpx" height="142rpx" :src="currentSku?.image" radius="12rpx"
              @click="getSkuImage(currentSku?.image)"></uv-image>
          </view>
          <view class="m-l-34">
            <view class="font-32">{{ formData.detailData.product_name || '--' }}</view>
            <view class="font-32 font-weight-bold m-t-18">￥{{ formData.number * (currentSku?.price / 100) }}
            </view>
          </view>
          <view class="iconX" @click="popup.close()">
            <uv-image width="48rpx" height="48rpx" :src="ASSETSURL + `x.png`"></uv-image>
          </view>
        </view>
        <view class="m-t-30" v-for="(item, index) in formData.detailData.goods_attr" :key="index">
          <view class="font-30">{{ item.attr_name }}</view>
          <view class="sortNameImage flex m-t-20">
            <view class="sort m-r-26" v-for="(item2, index2) in item.attr_values" :key="index2"
              @click="selectAttr(item.attr_name, item2.name)">
              <view class="nameImage flex align-ali"
                :class="{ 'sortActive': selectedAttrs[item.attr_name] === item2.name }">
                <view class="name font-28">
                  {{ item2.name }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="flex align-ali justify-bet m-t-40">
          <view class="font-30">购买数量</view>
          <view>
            <uv-number-box :disabledInput="true" bgColor2="#F3F3F3" bgColor="#FFF" inputWidth="78rpx"
              @change="valChange" :max="currentSku?.stock"></uv-number-box>
          </view>
        </view>
      </view>
    </uv-popup>
    <!-- 底部购物车 -->
    <view class="fbom fixed-bottom flex align-ali p-x-26 p-y-16 p-b-50">
      <view class="flex align-ali flex-col justify-cen clothesCart">
        <button open-type="contact" class="button">
          <view>
            <uv-image width="42rpx" height="42rpx" :src="ASSETSURL + `clothes.png`"></uv-image>
          </view>
          <view class="m-t-6 font-22" style="line-height: normal">客服</view>
        </button>
      </view>
      <view class="flex align-ali flex-col justify-cen clothesCart" @click="goPages('/packageOrder/shopCar/shopCar')">
        <view>
          <uv-image width="42rpx" height="42rpx" :src="ASSETSURL + `cart.png`"></uv-image>
        </view>
        <view class="m-t-6 font-22">购物车</view>
      </view>
      <view class="m-l-12">
        <dy-button width="250rpx" f_size="36rpx" btn_bg="#FFEBEC" f_color="#830102" @click="getCartBtn">
          加入购物车
        </dy-button>
      </view>
      <view class="m-l-12">
        <dy-button width="250rpx" f_size="36rpx" @click="getImmediatelyBtn">
          立即购买
        </dy-button>
      </view>
      <!-- <view class="m-l-12 cartBtn font-32 flex align-ali justify-cen" @click="getCartBtn">加入购物车</view>
      <view class="m-l-12 immediatelyBtn font-32 flex align-ali justify-cen text-white" @click="getImmediatelyBtn">
        立即购买
      </view> -->
    </view>
    <dy-login ref="login"></dy-login>
  </view>
</template>

<script setup>
import {
  getProductDetail,
  addCart,
  createOrder
} from '@/api/api';
import {
  ref,
  onMounted,
  reactive,
  computed,
  getCurrentInstance
} from 'vue';
import {
  useStore
} from 'vuex';
import {
  onReachBottom,
  onShow,
  onReady,
  onLoad
} from '@dcloudio/uni-app';
import {
  os,
  sys
} from '@/uni_modules/uv-ui-tools/libs/function/index.js';
import route from '@/uni_modules/uv-ui-tools/libs/util/route.js';
import {
  useCounter
} from '@/mixins/userHooks';
import { getBaseInfo } from '@/api/api';
const {
  getUserInfo,
  userInfo,
  isLogin,
  tool
} = useCounter();
const popup = ref(null);
const login = ref(null);
const msgList = ref(null);
const selectedAttrs = reactive({}); // 新增选中状态存储对象 // 结构示例：{ 材质: "黄金", 长度: "40cm" }
const formData = reactive({
  list: [],
  detailData: {
    goods_attr: [],
    goods_attr_value: []
  },
  number: 1 //数量
});
const { proxy } = getCurrentInstance();
onLoad((ope) => {
  if (ope.id) {
    getProductDetails(ope.id);
  }
  get_configuration()
});
const get_configuration = async () => {
	let { data } = await getBaseInfo();

	msgList.value = [
		{ name: '【运输说明】', content: data.find((item) => item.type == 12)?.content || '' },
		{ name: '【退换说明】', content: data.find((item) => item.type == 9)?.content || '' },
		{ name: '【保养说明】', content: data.find((item) => item.type == 7)?.content || '' },
		{ name: '【其它说明】', content: data.find((item) => item.type == 13)?.content || '' }
	];
};
// 立即购买
const getImmediatelyBtn = () => {
  console.log(currentSku.value, '立即购买');
  if (!userInfo.value.mobile) {
    login.value.open();
    return;
  }
  if (popup.value.showPopup) {
    console.log(currentSku.value, '立即购买');
    console.log('库存', currentSku.value.stock)
    if (!currentSku.value.stock) {
      proxy.$tool.alert('库存不足')
      return
    }
    route({
      url: 'pagesA/pages/productList/orderConfirmation',
      params: {
        add_type: 1,
        buy_mode: 1,
        product_id: currentSku.value.product_id,
        product_attr_unique: currentSku.value.unique,
        productData: JSON.stringify(currentSku.value), //选中商品数据
        number: formData.number, //数量
        price: currentSku?.value.total_price * formData.number || currentSku?.value.price * formData.number, //价格
        product: encodeURIComponent(JSON.stringify(formData.detailData)) //整个商品数据
      }
    });
  } else {
    // 打开弹窗
    popup.value.open();
  }
};
const getSkuImage = (e) => {
  console.log(e, '获取sku图片');
  // 预览图片
  uni.previewImage({
    urls: [e],
    current: e
  });
};
// 加入购物车
const getCartBtn = () => {
  if (!userInfo.value.mobile) {
    login.value.open();
    return;
  }
  if (popup.value.showPopup) {
    let data = {
      add_type: 1,
      product_id: currentSku.value.product_id,
      unique: currentSku.value.unique,
      cart_num: formData.number
    };
    addCart(data).then((res) => {
      console.log(res, currentSku, '加入购物车');
      // 加入购物车
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
      popup.value.close();
    });
  } else {
    // 打开弹窗
    popup.value.open();
  }
};
// 关闭弹窗
const closePopup = () => {
  popup.value.close();
};

// 计算当前匹配的SKU
const currentSku = computed(() => {
  // 获取属性顺序（根据 goods_attr 的顺序）
  const attrOrder = formData.detailData.goods_attr.map((item) => item.attr_name);

  // 生成当前选中的规格组合
  const selectedValues = attrOrder.map((attrName) => selectedAttrs[attrName]).filter(Boolean); // 过滤未选择的属性

  // 当选择不完整时返回 null
  if (selectedValues.length !== attrOrder.length) return null;

  // 生成规格字符串（顺序与SKU一致）
  const sukKey = selectedValues.join(',');

  // console.log('当前选中:', attrOrder, selectedValues, sukKey, formData.detailData.goods_attr_value)
  console.log('当前选中:', sukKey, formData.detailData.goods_attr_value);
  // 查找匹配的SKU
  return formData.detailData.goods_attr_value.find((item) => item.suk === sukKey);
});
// 选择规格
const selectAttr = (attrName, value) => {
  selectedAttrs[attrName] = value;
  // console.log('当前选中:', selectedAttrs) // 调试用
};
// 数量改变
const valChange = (e) => {
  // console.log(e, currentSku.value, '-=-----------');
  formData.number = e.value;
};
// 商品详情方法
const getProductDetails = async (e) => {
  const res = await getProductDetail({
    product_id: e
  });
  // 处理属性数据
  res.data.goods_attr.forEach((item) => {
    item.attr_values = item.attr_values.split(',').map((value) => ({
      name: value.trim()
    }));
  });
  // 处理属性数据
  res.data.goods_attr_value.forEach((item) => {
    item.price2 = item.price;
  });
  // 初始化选中状态（选择第一个）
  res.data.goods_attr.forEach((item) => {
    if (item.attr_values.length > 0) {
      selectedAttrs[item.attr_name] = item.attr_values[0].name;
    }
  });

  formData.detailData = res.data;
};

// 跳转
const goPages = (e) => {
  if (!userInfo.value.mobile) {
    login.value.open();
    return;
  }
  route({
    url: e
  });
};
</script>
<style lang="scss" scoped>
::v-deep .uv-cell__body {
  padding: 24rpx 32rpx !important;
}

::v-deep .uv-number-box__plus {
  background: transparent !important;
}

::v-deep .uv-number-box__minus {
  background: transparent !important;
}

::v-deep .uv-number-box__input {
  width: 78rpx !important;
  height: 40rpx !important;
  border-radius: 12rpx !important;
}

::v-deep .uvicon-plus {
  font-size: 24rpx !important;
}

::v-deep .uvicon-minus {
  font-size: 24rpx !important;
}

.box {
  padding-bottom: 210rpx;
  box-sizing: border-box;
  background: #fff;
}

.collect-text {
  font-family: Source Han Sans CN;
  font-weight: 400;
  line-height: 170%;
  letter-spacing: 0px;
  color: #999999;
}

.material {
  width: auto;
  height: 74rpx;
  background: #f6f6f6;
  padding: 0 16rpx;
  box-sizing: border-box;
}

.prodTitle {
  position: relative;
  /* 确保伪元素相对于此容器定位 */

  .prodTitleText {
    &::before {
      content: '';
      position: absolute;
      left: 0rpx;
      /* 调整为较小的负值 */
      top: 50%;
      transform: translateY(-50%);
      width: 8rpx;
      height: 24rpx;
      background: #830102;
    }
  }
}

.fbom {
  width: 100vw;
  // height: 160rpx;
  background: #fff;
  border-color: #d9d9d9 !important;

  .clothesCart {
    width: 100rpx;
  }

  .cartBtn {
    width: 250rpx;
    height: 98rpx;
    background: #ffebec;
    border-radius: 12rpx;

  }

  .immediatelyBtn {
    width: 250rpx;
    height: 98rpx;
    background: #830102;
    border-radius: 12rpx;

  }
}

.specifications {
  // width: 100%;
  height: 580rpx;
  overflow-y: auto;

  .sortNameImage {
    .sort {
      .nameImage {
        padding: 10rpx 23rpx;
        box-sizing: border-box;
        color: #2b2b2b;
        // border: 2rpx solid #999999;
        border-radius: 8rpx;
        background: #efefef;
      }

      .sortActive {
        // border: 2rpx solid #1e1e1e !important;
        background: #951d1d;

        .name {
          color: #fff !important;
        }
      }
    }
  }
}

.iconX {
  margin-left: auto;
  margin-bottom: auto;
}
</style>